package school.util;

import java.sql.*;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBUtil {
	private DBUtil() {
	}

	// private static Properties p = new Properties();
	private static DataSource ds;
	static {
		try {
			Context ic = new InitialContext();
			ds = (DataSource) ic.lookup("java:comp/env/jdbc/news");
		} catch (NamingException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

		// try {
		// p.load(DBUtil.class.getClassLoader().getResourceAsStream(
		// "db.properties"));
		// // Class.forName("com.mysql.jdbc.Driver");
		// Class.forName(p.getProperty("driver"));
		// } catch (Exception e) {
		// // TODO 自动生成的 catch 块
		// e.printStackTrace();
		// }
	}

	// static final String url = p.getProperty("url");//
	// "jdbc:mysql://localhost:3306/soarroad";

	// public static Connection getConnection() {
	// Connection con = null;
	// try {
	// con = DriverManager.getConnection(url, p.getProperty("user"),
	// p.getProperty("pass"));
	// return con;
	// } catch (SQLException e) {
	// e.printStackTrace();
	// throw new RuntimeException(e);
	// }
	// }
	public static Connection getConnection() {
		Connection con = null;
		try {
			con = ds.getConnection();
			System.out.println("connection:" + con.hashCode());
		} catch (SQLException e) {
			// 忽略
			e.printStackTrace();
		}
		return con;
	}

	public static void close(ResultSet rs, Statement s, Connection c) {
		close(rs);
		close(s);
		close(c);
	}

	public static void close(Statement s) {
		if (s != null)
			try {
				s.close();
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
	}

	public static void close(ResultSet s) {
		if (s != null)
			try {
				s.close();
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
	}

	public static void close(Connection s) {
		if (s != null)
			try {
				s.close();
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
	}

	/**
	 * 通用的CUD操作方法
	 * 
	 * @param sql
	 * @param args
	 * @return
	 */
	public static int executeUpdate(String sql, Object... args) {
		Connection con = getConnection();
		PreparedStatement ps = null;
		try {
			ps = con.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			int r = ps.executeUpdate();
			System.out.println(r + ">>>>>>>>>>>>>>>>>>");
			return r;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(null, ps, con);
		}

		return 0;
	}
}
